import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';

import 'package:get/get.dart';
import 'package:get/get_navigation/src/routes/default_transitions.dart';
import 'package:yysk_app/pages/nft_pages/danation/danation_choose_goods_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/transaction_password_page.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:oktoast/oktoast.dart';
import 'danation_confirm_controller.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';

class DanationConfirmWidget extends GetView<DanationConfirmController> {
  static const path = '/danationConfirm';
  DanationConfirmWidget({super.key});

  // 新增：平台内部按钮选中状态
  final RxBool isPlatformSelected = true.obs;
  final RxBool isZcPlatformSelected = true.obs;
  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          SizedBox(
            width: context.width,
            child: ImageAssetWidget(
              width: 375.px,
              height: 196.px,
              imageUrl: 'static/images/setting/give_top_bg@2x.png',
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: top),
            child: Column(
              children: [
                CustomAppBar2(
                  title: '',
                  context: context,
                  beforBack: () {
                    Navigator.of(context).pop();
                  },
                ),
                Expanded(
                  child: _contentList(context: context, controller: controller),
                ),
                _footer(context: context),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _contentList({
    required BuildContext context,
    required DanationConfirmController controller,
  }) {
    final GlobalController globalController = Get.find();

    return Obx(
      () => ListView(
        children: [
          Center(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: AppColors.backgroundColor, width: 3),
                boxShadow: [
                  BoxShadow(
                    color: AppColors.backgroundColorBlack.withAlpha(25),
                    offset: const Offset(0, 14),
                    blurRadius: 24,
                    spreadRadius: 0,
                  ),
                ],
              ),
              child: LazyImage(
                imageUrl: '${controller.url}',
                borderRadius: 12,
                width: 114.px,
                height: 114.px,
              ),
            ),
          ),
          hiSpace(height: 10),
          Center(
            child: Text(
              '转赠数量：${controller.list.length}',
              style: TextStyle(
                fontSize: 20.px,
                color: Color(0xFF3A634F),
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
          hiSpace(height: 10),
          SizedBox(
            height: 40.px,
            child: Stack(
              children: [
                Positioned(
                  left: 26.px,
                  top: 10.px,
                  height: 20.px,
                  child: Text(
                    '接收平台',
                    style: TextStyle(
                      fontSize: 14.px,
                      color: Color(0xFF3A634F),
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),

                Positioned(
                  right: 20.px,
                  top: 10.px,
                  // width: 70.px,
                  height: 20.px,
                  child: Obx(
                    () => TextButton(
                      onPressed: () {
                        // isZcPlatformSelected.value = !isZcPlatformSelected.value;
                      },
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(
                          isZcPlatformSelected.value
                              ? Color(0xFFE3E7E2)
                              : Color(0xFFE0E0E0),
                        ),
                        shape: WidgetStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        padding: WidgetStateProperty.all(
                          EdgeInsets.symmetric(horizontal: 12, vertical: 2),
                        ),
                        minimumSize: WidgetStateProperty.all(Size(0, 28)),
                      ),
                      child: Text(
                        (controller.type.value == '2' &&
                                controller.transferTypeWay.value == 1)
                            ? '臻藏平台'
                            : '平台内部',
                        style: TextStyle(
                          color:
                              isZcPlatformSelected.value
                                  ? Color(0xFF3A634F)
                                  : Color(0xFF767676),
                          fontSize: 12.px,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          hiSpace(height: 5),

          Padding(
            padding: EdgeInsets.fromLTRB(30, 10, 30, 0),
            child: TextField(
              controller: controller.addressController,
              onChanged: (value) {},
              maxLines: 1,
              style: TextStyle(
                fontSize: 15.px,
                color: AppColors.backgroundColorBlack,
              ),
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.symmetric(vertical: 14),
                border: InputBorder.none,
                hintText: '输入账号接受地址',
                hintStyle: const TextStyle(color: AppColors.fontColorGreyLight),
                suffixIcon: IconButton(
                  color: AppColors.fontColorGrey,
                  onPressed: () {
                    controller.addressController.text = '';
                  },
                  iconSize: 18,
                  icon: Image.asset(
                    'static/images/setting/danation_close@2x.png',
                    width: 25,
                    height: 25,
                  ),
                ),
              ),
            ),
          ),
          Divider(
            color: Color(0xFFF2F2F2),
            thickness: 1,
            indent: 30,
            endIndent: 30,
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(30, 10, 30, 15),
            child: Text(
              '请确保地址无误，否则NFT将无法找回！',
              style: TextStyle(fontSize: 12.px, color: Color(0xFFFF0000)),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(25, 11, 30, 0),
            child: Text(
              '请选择支付方式',
              style: TextStyle(fontSize: 16.px, color: Color(0xFF000000)),
            ),
          ),
          hiSpace(height: 10),
          controller.dataList.isNotEmpty
              ? _listViewWidget(context)
              : SizedBox(),

          Padding(
            padding: EdgeInsets.fromLTRB(25, 11, 30, 0),
            child: Text(
              '转赠须知',
              style: TextStyle(fontSize: 16.px, color: Color(0xFF000000)),
            ),
          ),
          // Padding(
          //   padding: EdgeInsets.fromLTRB(25.px, 12, 25.px, 15),
          //   child: const Text(
          //     '1、藏品转出不可撤销，可通知对方转回；\n '
          //     '2、转赠需谨慎，如因用户私下交易造成的资产损失，平台概不负责。\n',
          //     style: TextStyle(color: Color(0xFF9E9E9E), fontSize: 12.px),
          //   ),
          // ),
          Padding(
            padding: EdgeInsets.fromLTRB(25.px, 12, 25.px, 15),
            child: HtmlWidget(
              ''' <div>
                        ${globalController.staticInfo.value?.transferNotice ?? ''}
                        </div>
                        ''',
              textStyle: TextStyle(color: Color(0xFF9E9E9E), fontSize: 12.px),
              customWidgetBuilder: (element) {
                if (element.localName == 'img') {
                  // consoleLog('String===${element.attributes['src']}');
                  return LazyImage(
                    imageUrl: '${element.attributes['src']}',
                    boxFit: BoxFit.fitWidth,
                    width: context.width,
                    aotuHeight: true,
                  );
                }
                return null;
              },
            ),
          ),
        ],
      ),
    );
  }

  _footer({required BuildContext context}) {
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(5.px, 4.px, 10.px, 14.px),
      child: Center(
        child: ButtonWidget(
          label: "确认转赠",
          width: 322,
          height: 54,
          fontSize: 18.px,
          imageBg: 'static/images/btm.png',
          contentType: ContentType.other,

          onPressed: () {
            final GlobalController globalController = Get.find();
            if (globalController.user.value!.isSm != true) {
              showConfirmDialog(
                context: context,
                fontSize: 16,
                message: '请先完成实名认证',
                actions: [
                  ActionModel(
                    label: '取消',
                    colorStart: AppColors.backgroundColorGreyF8,
                    colorEnd: AppColors.backgroundColorGreyF8,
                    fontColor: AppColors.fontColor,
                  ),
                  ActionModel(
                    label: '立即认证',
                    onPressed: () {
                      Get.toNamed(SettingRealNameAuthPage.path);
                    },
                  ),
                ],
              );
              return;
            }
            if (globalController.user.value?.transactionPassword == null) {
              controller.isSetPayPassword();
              return;
            }
            controller.securityPassword.value = '';
            TransactionPasswordDialog.show(
              Get.context!,
              onCompleted: (password) {
                controller.securityPassword.value = password;
                controller.sub();
              },
              onCancel: () {
                // 取消回调（可选）
                controller.securityPassword.value = '';
              },
            );
          },
        ),
      ),
    );
  }

  Widget _listViewWidget(BuildContext context) {
    return Obx(
      () => Column(
        children: [
          ...controller.dataList.asMap().entries.map((entry) {
            final index = entry.key;
            final item = entry.value;
            return GestureDetector(
              onTap: () {},
              child: Container(
                padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                margin: EdgeInsets.fromLTRB(14, 9, 14, 0),
                height: 65.px,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.px),
                  border: Border.all(color: Colors.white12),
                  color: AppColors.backgroundColorLightGrey,
                ),
                child: Obx(
                  () => Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        onTap: () {
                          var iterator = controller.dataList.iterator;
                          while (iterator.moveNext()) {
                            var item = iterator.current;
                            item.isSelect = false;
                          }
                          controller.dataList[index].isSelect = true;
                          controller.transferType.value =
                              controller.dataList[index].transferType ?? '';
                          controller.drawerCount.value++;
                        },
                        child: SizedBox(
                          width: 14.px,
                          height: 14.px,
                          child: Image.asset(
                            (controller.dataList[index].isSelect ?? false)
                                ? 'static/images/setting/danation_selected@2x.png'
                                : 'static/images/setting/danation_nomal@2x.png',
                            width: 14.px,
                            height: 14.px,
                          ),
                        ),
                      ),
                      SizedBox(width: 11.px),
                      Text(
                        '${controller.drawerCount}',
                        style: TextStyle(fontSize: 0),
                      ),
                      SizedBox(
                        width: 30.px,
                        height: 30.px,
                        child: LazyImage(
                          imageUrl: '${item.icon}',
                          width: 30.px,
                          height: 30.px,
                        ),
                      ),
                      SizedBox(width: 15.px),
                      Expanded(
                        child: Text(
                          controller.dataList[index].transferType == 'AMOUNT'
                              ? '金额支付'
                              : '积分支付',
                          style: TextStyle(
                            color: AppColors.backgroundColorBlack,
                            fontSize: 16.px,
                            overflow: TextOverflow.ellipsis,
                          ),
                          textAlign: TextAlign.left,
                        ),
                      ),

                      SizedBox(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              '需支付${controller.dataList[index].transferType == 'AMOUNT' ? '￥' : ''}${controller.dataList[index].amount}',
                              style: TextStyle(
                                color: AppColors.backgroundColorBlack,
                                fontSize: 14.px,
                                overflow: TextOverflow.ellipsis,
                              ),
                              textAlign: TextAlign.right,
                            ),

                            (controller.dataList[index].transferType ==
                                        'INTEGRAL' ||
                                    controller.dataList[index].transferType ==
                                        'POINTS')
                                ? Text(
                                  '已拥有${controller.dataList[index].availableAmount}',
                                  style: TextStyle(
                                    color: AppColors.fontColor9E,
                                    fontSize: 12.px,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  textAlign: TextAlign.right,
                                )
                                : SizedBox(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),
        ],
      ),
    );
  }
}
